<template>
  <el-row style="height:100%">
    <page @buttons="configPermissions">
      <pageheader :event="'offonPopUp'" :isShow="buttonPermissions.isAdd">数据权限管理</pageheader>
      <div class="page-content">
        <el-card class="box-card">
          <el-row>
            <Cascader
              :value="company_id_arr"
              :options.sync="options"
              :width="'300px'"
              :changeEvent="'roleDataChange'"
            >所属企业：
            </Cascader>
            <SearchInput
              style="margin-left: 20px"
              @roleSearch="roleSearch"
              :searchEvent="'roleSearch'"
              :value.sync="keywords"
              :searchText="'请输入数据角色名称'"
              ref="clearText"
            >搜索：
            </SearchInput>
          </el-row>
          <el-table :data="dataTable" size="small" stripe>
            <el-table-column type="expand">
              <template slot-scope="props">
                <div style="display: inline-block;">
                  <h4 style="font-size:16px">指标权限：</h4>
                  <span v-for="item in props.row.indicator_list" :key="item.id" style="display:inline-block; padding: 5px 20px">
                    {{item.name}}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>
            <el-table-column label="数据角色名称" prop="org_auth_name" align="left" sortable></el-table-column>
            <el-table-column label="所属企业" prop="company_name" align="center" sortable></el-table-column>
            <el-table-column label="对应节点名称" prop="name" align="center" sortable></el-table-column>
            <el-table-column label="组织架构类型" prop="org_type_name" align="center" sortable></el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template slot-scope="scope">
                <el-button v-if="buttonPermissions.isWatch"
                  @click="roleData(scope.row)" size="small" >详情</el-button>
                   <el-button type="danger"  v-if="buttonPermissions.isDelete" 
                  @click="deleteRole(scope.row)" size="small"  >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background
                         layout="total,sizes,prev,pager, next"
                         @current-change="currentChange"
                         @size-change="sizeChange"
                         :page-sizes="pagination.pageSizes"
                         :page-size.sync="pagination.pageSize"
                         :total="pagination.total"
                         :current-page.sync="pagination.currentPage"
                         class="paging fr">
          </el-pagination>
        </el-card>
        <el-dialog  v-dialogDrag title="数据权限管理" :visible.sync="isShow" @close="closeDialog('ruleForm')" width="900px"
                   :modal-append-to-body="false" :close-on-click-modal="false">
          <el-row>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px">
              <el-form-item label="数据角色名称：" prop="org_auth_name">
                <el-input v-model="ruleForm.org_auth_name" size="small" style="width:500px"></el-input>
              </el-form-item>
              <el-form-item label="组织架构：" prop="name" v-show="!isDisabled">
                <el-cascader
                  v-model="OrgVoAuthValue"
                  :options="OrgVoAuth"
                  @change="handleItemChange"
                  @visible-change="visibleChange"
                  size="small"
                  filterable
                  :props="OrgVoAuthProps"
                  expand-trigger="hover"
                  change-on-select
                  style="width:500px"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="组织架构：" v-show="isDisabled" prop="name">
                <el-input  v-model="ruleForm.name" size="small" :disabled="true" style="width:500px"></el-input>
              </el-form-item>
              <el-form-item label="指标：" v-if="isShowRegionList" prop="indicator_arr">
                <el-checkbox-group v-model="ruleForm.indicator_arr" size="small" @change="checkChange" style="width:80%">
                  <el-checkbox v-for="item in regionList" v-if="item.type == 1"
                               :label="item.key" :key="item.key" border style="width: 120px; margin:10px 10px">
                    {{item.name}}
                    <el-popover v-if="item.desc" placement="right-start" title="说明:" width="300" trigger="hover"
                                :content="item.desc">
                      <i slot="reference" class="el-icon-question"></i>
                    </el-popover>
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="人脸指标：" v-if="isShowRegionListFace" prop="indicator_arr_face">
                <el-checkbox-group v-model="ruleForm.indicator_arr_face" size="small" @change="faceCheckChange" style="width:80%">
                  <el-checkbox v-for="item in regionList" v-if="item.type == 2"
                               :label="item.key" :key="item.key" border style="width: 120px; margin:10px 10px">
                    {{item.name}}
                    <el-popover v-if="item.desc" placement="right-start" title="说明:" width="300" trigger="hover"
                                :content="item.desc">
                      <i slot="reference" class="el-icon-question"></i>
                    </el-popover>
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="指标：" v-if="!isShowRegionList && !isShowRegionListFace">
                <span style="color:#ccc;">该权限下指标为空</span>
              </el-form-item>

            </el-form>
          </el-row>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <el-button v-if="(!isDisabled && buttonPermissions.isAdd) || (isDisabled && buttonPermissions.isModify)"
              type="primary" @click="confirmDialog('ruleForm')" size="small">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
body{
  .el-message-box__wrapper{
    .shanchuClass{
      .el-message-box__content{
        .el-message-box__message{
          p{
            max-height: 200px;
            overflow-y: auto;
            width: 100%;
            word-break:break-all;
          }
        }
      }
    }
  }
}
.page-content {
  padding: 15px;
  .fr {
    float: right;
  }
  .el-table {
    margin-bottom: 10px;
  }
  .paging {
    margin: 15px;
    height: 28px;
  }
}
</style>
<script>
import page from "@/components/page/page";
import pageheader from "@/components/page/pageheader";
import SearchInput from "@/components/sys/assembly/searchinput";
import Cascader from "@/components/sys/assembly/elcascader";
export default {
  data() {
    return {
      pageTitle: "数据权限管理",
      options:[],//级联控件 所属企业
      isShow: false,//是否显示模态框
      isDisabled: false,//是否是修改状态
      keywords:'',//搜素数据权限名称
      regionList:[],//区域权限list
      dataTable:[],//表格数据
      pagination:{
        total:0,//总条目数
        currentPage:1,//当前页数
        pageSize:10,//每页显示条目个数
        pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
      },//表格分页参数
      ruleForm:{
        org_auth_name:'',//数据角色名称
        indicator_str:'',
        indicator_arr:[],
        indicator_str_face:'',
        indicator_arr_face:[],
        name:'',//组织架构名称
      },//模态框form表单
      rules: {
        org_auth_name: [{ required: true, message: "请输入数据角色名称", trigger: "blur"}],
      },//form表单验证
      props: {
        label: 'name',
      },//树形控件配置选项
      company_id:'',//选择企业ID
      company_id_arr:[],//选择企业ID arr
      buttonPermissions:{
        isAdd:true,
        isModify:false,
        isWatch:false,
        isDelete:false,
      },
      OrgVoAuthValue:[],
      OrgVoAuth:[],
      OrgVoAuthProps:{
        value: 'value',
        label: 'name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly:'true',
      },
      isShowRegionList:false,
      isShowRegionListFace:false,
    };
  },
  components: {
    page,
    pageheader,
    SearchInput,//搜索框组件
    Cascader,//级联选择器组件
  },
  created() {
    //判断是否有按钮权限
    if(sessionStorage.buttonPermissions){
      this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
    }
    //初始化页面
    this.getTree()
    this.getOrgAuthNodes()
  },
  mounted() {
    //新增按钮点击事件
    this.$Bus.$on("offonPopUp", () => {
      this.isShow = true;
      this.isDisabled = false;
    });
    //所属企业change事件
    this.$Bus.$on("roleDataChange", data => {
      this.company_id = data.slice(-1)[0];
      this.$Bus.$emit('Loading',true);
      this.getOrgAuthList(this.company_id)
    });
  },
  beforeDestroy(){
    this.$Bus.$off('offonPopUp')
    this.$Bus.$off('roleDataChange')
  },
  methods: {
    //表格序号显示方法
    indexMethod(index){
      return index + ((this.pagination.currentPage - 1) * this.pagination.pageSize) + 1
    },
    //配置按钮权限，根据权限不同调整表头渲染参数
    configPermissions(val){
      let buttonPermissions = val
      let menuButtonPermissions = [];//按钮权限数组
      buttonPermissions.forEach(e =>{
        for(let key in e){
          if(key == 'menu_code'){
            menuButtonPermissions.push(e[key])
          }
        }
      });
      this.buttonPermissions.isAdd = menuButtonPermissions.includes('roleDataAdd') ? true : false; //是否有新增权限
      this.buttonPermissions.isModify = menuButtonPermissions.includes('roleDataModify') ? true : false; //是否有修改权限
      this.buttonPermissions.isWatch = menuButtonPermissions.includes('roleDataWatch') ? true : false; //是否有查看权限
      this.buttonPermissions.isDelete = menuButtonPermissions.includes('roleDataDelete') ? true : false; //是否有查看权限
    },
    //获取企业tree
    getTree(){
      let url = '/sys/report_assist_new/company_tree';
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          recursion(data.data);
          function recursion(val) {
            if(val.length){
              for(let i in val){
                val[i].value = val[i].id;
                val[i].label = val[i].company_name;
                val[i].parent_id_str = val[i].parent_name_list.join('/');
                if(val[i].children && val[i].children.length){
                  recursion(val[i].children)
                }else{
                  delete val[i].children
                }
              }
            }
          }
          this.options = data.data
          this.company_id = data.data[0].id
          this.company_id_arr.push(data.data[0].id)
          this.getOrgAuthList(data.data[0].id)
        }
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //组织构架change事件
    handleItemChange(val){
      let selectedData = recursionOrgVoAuth(this.OrgVoAuth,0);
      function recursionOrgVoAuth(list,n) {
        if(n === val.length) return list;
        for (let i = 0; i <= list.length; i++) {
          if (val[n] === list[i].value) {
            return list[i].children ? recursionOrgVoAuth(list[i].children,++n) : [];
          }
        }
      }
      // console.log(selectedData,'selectedData');
      if(selectedData.length == 0){
        let id = val[val.length-1].split('-')[0];
        let type = val[val.length-1].split('-')[1];
        let url = '/sys/org_auth/nodes?foreign_key='+ id +'&org_type=' + type;
        this.$api.get(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          if(data){
            // console.log(data.data,'data');
            data.data.forEach(x =>{
              x.children = [];
              x.value = x.foreign_key + '-' + x.org_type
            });
            //递归OrgVoAuth，找出选中的子级赋值
            recursionData(this.OrgVoAuth,0);
            function recursionData(list,n) {
              // console.log(list,'list');
              // console.log(n,'n');
              if(n === val.length) {
                return list.push(...data.data)
              }else{
                for (let i = 0; i <= list.length; i++) {
                  if (val[n] === list[i].value) {
                    //当data数据为空的时候停止递归函数，并删除子级的children
                    if(n === (val.length -1) && data.data.length === 0){
                      // console.log('delete');
                      // console.log(this.$set);
                      delete list[i].children
                      return
                    }else{
                      return recursionData(list[i].children,n+1)
                    }
                  }
                }
              }
            }
          }
        })
      }
    },
    //组织架构选中事件
    visibleChange(val){
      if(!val && this.OrgVoAuthValue.length){
        this.$nextTick(()=>{
          let list = {}
          list.org_type = this.OrgVoAuthValue[this.OrgVoAuthValue.length-1].split('-')[1]
          list.foreign_key =this.OrgVoAuthValue[this.OrgVoAuthValue.length-1].split('-')[0]
          this.getOrgAuthIndicators(list)
        })
      }
    },

    getOrgAuthNodes(){
      let url = '/sys/org_auth/nodes'
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          data.data.forEach(x=>{
            x.children = [];
            x.value = x.foreign_key + '-' + x.org_type
          })
          this.OrgVoAuth = data.data
        }
      })
    },

    //获取数角色限列表
    getOrgAuthList(company_id='',page='1',page_size='10',keywords=''){
      let url = '/sys/org_auth/list?company_id='+ company_id +
        '&page='+ page +'&page_size=' + page_size + '&keywords=' + encodeURIComponent(keywords);
      this.$api.get(url)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        let _data = data.data
        //判断接口返回正常
        if(_data){
          this.dataTable = _data.dataList ? _data.dataList.map( x =>{
            x.org_type_name = x.org_type == 1 ? '企业' :
              x.org_type == 2 ? '案场' : '区域';
            return x
          }): [];
          this.pagination.total = _data.dataCount;
          this.pagination.currentPage = _data.pageCode;
          this.pagination.pageSize = _data.pageSize;
        }
        this.$Bus.$emit('Loading',false)
      })
      //回传参数为空试
      .catch(err=>{
         console.log(err);
        this.dataTable = [];
        this.$Bus.$emit('Loading',false)
      })
    },
    //获取可使用指标列表
    getOrgAuthIndicators(list){
      let url = '/sys/org_auth/indicators?org_type='+ list.org_type + '&foreign_key=' + list.foreign_key;
      this.$api.get(url)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.regionList = data.data;
          let arr = this.regionList.filter(x=>x.type == 1)
          let arr_face = this.regionList.filter(x=>x.type == 2)
          this.isShowRegionList = arr.length ? true :false
          this.isShowRegionListFace = arr_face.length ? true :false

          this.$Bus.$emit('Loading',false)
        }
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //关闭模态框
    closeDialog(formName){
      this.resetForm(formName)
      this.$Bus.$emit('Loading',false)
      this.ruleForm.isAdmin = '';
      this.ruleForm.org_auth_name = '';
      this.ruleForm.indicator_arr = [];
      this.ruleForm.indicator_str = '';
      this.ruleForm.indicator_arr_face = [];
      this.ruleForm.indicator_str_face = '';
      this.isShowRegionList = false
      this.isShowRegionListFace = false
      this.OrgVoAuthValue = [];
      this.regionList = [];//清空可使用指标列表
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //每页显示条目个数change事件
    sizeChange(val){
      this.$Bus.$emit('Loading',true)
      this.getOrgAuthList(this.company_id,this.pagination.currentPage,val,this.keywords)
    },
    //分页change事件
    currentChange(val){
      this.$Bus.$emit('Loading',true)
      this.getOrgAuthList(this.company_id,val,this.pagination.pageSize,this.keywords)
    },
    //搜索按钮点击事件
    roleSearch(data) {
      this.$Bus.$emit('Loading',true)
      this.keywords = data
      this.getOrgAuthList(this.company_id,1,this.pagination.pageSize,data)
    },
    //修改按钮点击事件
    roleData(data){
      this.isShow = true;
      this.isDisabled = true;
      this.$Bus.$emit('Loading',true)
      this.ruleForm.org_auth_name = data.org_auth_name
      this.ruleForm.name = data.name
      this.ruleForm.id = data.id
      let indicator_list = data.indicator_list.filter(x=>x.type == 1)
      let indicator_list_face = data.indicator_list.filter(x=>x.type == 2)
      this.ruleForm.indicator_arr = indicator_list.map(x=>x.key)
      this.ruleForm.indicator_arr_face = indicator_list_face.map(x=>x.key)
      this.ruleForm.indicator_str =indicator_list.map(x=>x.id).join(',')
      this.ruleForm.indicator_str_face = indicator_list_face.map(x=>x.id).join(',')
      this.getOrgAuthIndicators(data)
    },
    //新增保存
    addCompany(url, data) {
      this.$api.post(url, data)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if (data) {
          this.isShow = false
          this.getOrgAuthList(this.company_id,this.pagination.currentPage,this.pagination.pageSize,this.keywords)
          this.$message({
            message: "新增成功",
            type: "success"
          });
        }else{
          this.$Bus.$emit('Loading',false)
        }
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //模态框保存按钮
    confirmDialog(formName) {
      let data = {};
      let model = null;
      let url = ''
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.isDisabled && (this.ruleForm.indicator_arr.length == 0 && this.ruleForm.indicator_arr_face.length == 0)){
            this.$message.error('请选择数据指标')
            return
          }else if(!this.isDisabled && (this.ruleForm.indicator_arr.length == 0 && this.ruleForm.indicator_arr_face.length == 0)){
            this.$message.error('请选择组织架构和数据指标')
            return
          }
          this.$Bus.$emit('Loading',true)
          model = this.$refs[formName].model;
          let indicator_arr = [...this.ruleForm.indicator_str.split(','),...this.ruleForm.indicator_str_face.split(',')]
          if (this.isDisabled) {
            data.indicator_str = indicator_arr.join(',')
            data.org_auth_name  = model.org_auth_name
            url = "/sys/org_auth/update?id=" + this.ruleForm.id;
            this.orgUpdate(url, data);
          } else {
            data.indicator_str = indicator_arr.join(',')
            data.foreign_key  = this.OrgVoAuthValue[this.OrgVoAuthValue.length-1].split('-')[0]
            data.org_auth_name  = model.org_auth_name
            data.org_type  = this.OrgVoAuthValue[this.OrgVoAuthValue.length-1].split('-')[1]
            url = "sys/org_auth/add";
            this.addCompany(url, data);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //调用修改数据角色接口
    orgUpdate(url,data){
      this.$api.put(url,data)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if (data) {
          this.isShow = false
          this.getOrgAuthList(this.company_id,this.pagination.currentPage,this.pagination.pageSize,this.keywords)
          this.$message({
            message: "修改成功",
            type: "success"
          });
        }else{
          this.$Bus.$emit('Loading',false)
        }
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //多选的change
    checkChange(value){
      let indicator_str = []
      for(let i in this.regionList){
        if(value.includes(this.regionList[i].key)){
          indicator_str.push(this.regionList[i].id)
        }
      }
      this.ruleForm.indicator_str = indicator_str.join(',')
    },
    //多选的change
    faceCheckChange(value){
      let indicator_str = []
      for(let i in this.regionList){
        if(value.includes(this.regionList[i].key)){
          indicator_str.push(this.regionList[i].id)
        }
      }
      this.ruleForm.indicator_str_face = indicator_str.join(',')
    },
    //删除数据权限
    deleteRole(data){
      this.$confirm("是否删除‘"+ data.org_auth_name +"’？", "提示",{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center:true
      })
      .then(() => {
        this.$Bus.$emit('Loading',true)
        this.delData(data.id,0);
      })
      .catch(() => {
        return
      });
      // /sys/org_auth/del-org-auth-by-id
    },
    delData(id,isDelete)
    {
      let url='sys/org_auth/del-org-auth-by-id?org_auth_id='+id+'&isDelete='+isDelete;
      this.$api.delete(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data.data==null)
        {
          this.$Bus.$emit('Loading',true);
          this.getOrgAuthList(this.company_id);
          this.$message({
            message: "删除成功",
            type: "success"
          });
        }
        else{
          let nameArr=[];
          for(let i in data.data)
          {
            nameArr.push(data.data[i].user_name);
          }
          this.$Bus.$emit('Loading',false);
          this.$confirm(nameArr.join(' , ') , '以下用户正在使用该角色权限，是否删除？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            customClass:'shanchuClass',
            type: 'warning'
            }).then(() => {
              this.delData(id,1);
            }).catch(() => {});
        }
      })
      .catch(err=>{
        this.$message.error('删除失败');
        this.$Bus.$emit('Loading',true);
        console.log('错误');
      })
    }

  },
  watch: {}
};
</script>
